package code.generation;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import code.parser.Field;
import code.parser.Struct;

public class FieldSerializeJava implements FieldSerialize {
	@Override
	public String serialize(Struct struct) {

		StringBuilder sb = new StringBuilder();
		if (struct.namespace!=null) {
			sb.append("package   ").append(struct.namespace).append(";")
			.append(LINE_CHAR);
		}
		sb.append("public  class ").append(struct.name).append("{");
		sb.append(LINE_CHAR);
		for (int i = 0; i < struct.fieldList.size(); i++) {
			Field field = struct.fieldList.get(i);
			sb.append(TAB_CHAR);
			sb.append(field.access);
			sb.append(SPACE_CHAR);
			sb.append(field.type);
			sb.append(SPACE_CHAR);
			String name = field.name;
			name = replaceArray(field);
			sb.append(name);
			sb.append(";");
			sb.append(LINE_CHAR);
		}
		sb.append("}");

		return sb.toString();
	}

	public static String replaceArray(Field field) {
		if (field.name.contains("[")) {
			String re = "(\\s*)([a-zA-Z_0-9][a-zA-Z0-9_]*)(\\[\\d+\\])";
			Pattern p = Pattern.compile(re, Pattern.CASE_INSENSITIVE
					| Pattern.DOTALL);
			Matcher m = p.matcher(field.name);
			if (m.find()) {
				field.name = field.name.replace(
						m.group(3) , "[]");
				field.name = field.name + " = new " + field.type
						+ m.group(3);
			}
		}
		return field.name;
	}
}
